package com.macro.mall.portal.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import com.macro.mall.common.exception.Asserts;
import com.macro.mall.mapper.UmsMemberLevelMapper;
import com.macro.mall.mapper.UmsMemberMapper;
import com.macro.mall.mapper.UmsMemberStatisticsInfoMapper;
import com.macro.mall.model.*;
import com.macro.mall.portal.domain.MemberDetails;
import com.macro.mall.portal.service.UmsMemberCacheService;
import com.macro.mall.portal.service.UmsMemberService;
import com.macro.mall.portal.util.CityUtil;
import com.macro.mall.portal.util.WXUtils;
import com.macro.mall.portal.vo.WxLoginUserInfoVO;
import com.macro.mall.security.util.JwtTokenUtil;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 会员管理Service实现类
 * Created by macro on 2020/7/31.
 */
@Service
public class UmsMemberServiceImpl implements UmsMemberService {
    private static final Logger LOGGER = LoggerFactory.getLogger(UmsMemberServiceImpl.class);
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private UmsMemberMapper memberMapper;
    @Autowired
    private UmsMemberLevelMapper memberLevelMapper;
    @Autowired
    private UmsMemberStatisticsInfoMapper memberStatisticsInfoMapper;
    @Autowired
    private UmsMemberCacheService memberCacheService;
    @Value("${redis.key.authCode}")
    private String REDIS_KEY_PREFIX_AUTH_CODE;
    @Value("${redis.expire.authCode}")
    private Long AUTH_CODE_EXPIRE_SECONDS;
    @Value("${wx.appid}")
    private String WX_APP_ID;
    @Value("${wx.secret}")
    private String WX_SECRET;
    @Override
    public UmsMember getByUsername(String username) {
        UmsMember member = memberCacheService.getMember(username);
        if(member!=null) return member;
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(memberList)) {
            member = memberList.get(0);
            memberCacheService.setMember(member);
            return member;
        }
        return null;
    }

    @Override
    public UmsMember getById(Long id) {
        return memberMapper.selectByPrimaryKey(id);
    }

    @Override
    public void register(String username, String password, String telephone) {
        //验证验证码
//        if(!verifyAuthCode(authCode,telephone)){
//            Asserts.fail("验证码错误");
//        }
        //查询是否已有该用户
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        example.or(example.createCriteria().andPhoneEqualTo(telephone));
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(umsMembers)) {
            Asserts.fail("该用户已经存在");
        }
        //没有该用户进行添加操作
        UmsMember umsMember = new UmsMember();
        umsMember.setUsername(username);
        umsMember.setNickname(username);
        umsMember.setPhone(telephone);
        umsMember.setPassword(passwordEncoder.encode(password));
        umsMember.setCreateTime(new Date());
        umsMember.setStatus(1);
        //获取默认会员等级并设置
        UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
        levelExample.createCriteria().andDefaultStatusEqualTo(1);
        List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);
        if (!CollectionUtils.isEmpty(memberLevelList)) {
            umsMember.setMemberLevelId(memberLevelList.get(0).getId());
        }
        memberMapper.insert(umsMember);
        umsMember.setPassword(null);
    }

    @Override
    public String generateAuthCode(String telephone) {
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for(int i=0;i<6;i++){
            sb.append(random.nextInt(10));
        }
        memberCacheService.setAuthCode(telephone,sb.toString());
        return sb.toString();
    }

    @Override
    public void updatePassword(String username, String password, String updatePassword) {
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andUsernameEqualTo(username);
        List<UmsMember> memberList = memberMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(memberList)){
            Asserts.fail("该账号不存在");
        }
        //验证密码
        if(!memberList.get(0).getPassword().equals(password)){
            Asserts.fail("原密码错误");
        }
        UmsMember umsMember = memberList.get(0);
        umsMember.setPassword(passwordEncoder.encode(updatePassword));
        memberMapper.updateByPrimaryKeySelective(umsMember);
        memberCacheService.delMember(umsMember.getId());
    }

    @Override
    public UmsMember getCurrentMember() {
        SecurityContext ctx = SecurityContextHolder.getContext();
        Authentication auth = ctx.getAuthentication();
        System.out.println("11111111====anonymousUser"+auth.getPrincipal());
        if (auth.getPrincipal().equals("anonymousUser")){
            return null;
        }
        MemberDetails memberDetails = (MemberDetails) auth.getPrincipal();
        System.out.println(memberDetails.getUmsMember());

        return memberMapper.selectByPrimaryKey(memberDetails.getUmsMember().getId());
    }

    @Override
    public void updateIntegration(Long id, Integer integration) {
        UmsMember record=new UmsMember();
        record.setId(id);
        record.setIntegration(integration);
        memberMapper.updateByPrimaryKeySelective(record);
        memberCacheService.delMember(id);
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        UmsMember member = getByUsername(username);
        if(member!=null){
            return new MemberDetails(member);
        }
        throw new UsernameNotFoundException("用户名或密码错误");
    }

    @Override
    public String login(String username, String password) {
        String token = null;
        //密码需要客户端加密后传递
        try {
            UserDetails userDetails = loadUserByUsername(username);
            if(!passwordEncoder.matches(password,userDetails.getPassword())){
                throw new BadCredentialsException("密码不正确");
            }
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        } catch (AuthenticationException e) {
            LOGGER.warn("登录异常:{}", e.getMessage());
        }
        return token;
    }

    @Override
    public String refreshToken(String token) {
        return jwtTokenUtil.refreshHeadToken(token);
    }

    @Override
    public Map<String, String> wxLogin(WxLoginUserInfoVO wxLoginUserInfoVO) {
        Map<String, String> tokenMap=new HashMap<>();
        String token = null;
        String phone="";
        RestTemplate restTemplate =new RestTemplate();
        String url = String.format(
                "https://api.weixin.qq.com/sns/jscode2session?grant_type=client_credential&appid=%s&secret=%s&js_code=%s",
                WX_APP_ID, WX_SECRET, wxLoginUserInfoVO.getCode());
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
        String body = responseEntity.getBody();
        if (StringUtils.isBlank(body)){
            Asserts.fail("程序出错");
        }
        Map<String, Object> resMap = JSON.parseObject(body,Map.class);
        System.out.println(resMap);
        UmsMemberExample example = new UmsMemberExample();
        example.createCriteria().andOpenIdEqualTo(resMap.get("openid").toString());
        List<UmsMember> umsMembers = memberMapper.selectByExample(example);
        tokenMap.put("successKey",resMap.get("session_key").toString());
        String s = WXUtils.getUserInfo(wxLoginUserInfoVO.getEncryptedData(),resMap.get("session_key").toString(),wxLoginUserInfoVO.getIv()).toString();
        Map<String,Object> res = JSON.parseObject(s,Map.class);
        System.out.println("微信="+s);
        UmsMember umsMember = new UmsMember();
        SimpleDateFormat sdf =   new SimpleDateFormat( "yyyyMMddHHmm" );
        if(!umsMembers.isEmpty()){
            if (umsMembers.get(0).getStatus()==0){
                Asserts.fail("该用户已被禁用");
            }
            phone=umsMembers.get(0).getPhone();
            umsMember.setNickname(res.get("nickName").toString());
            umsMember.setPhone(null);
            umsMember.setCreateTime(new Date());
            umsMember.setCity(res.get("city").toString());
            umsMember.setGender((int)res.get("gender"));
            umsMember.setIcon(res.get("avatarUrl").toString());
            memberMapper.updateByPrimaryKeySelective(umsMember);
            UmsMemberStatisticsInfoExample memberStatisticsInfoExample = new UmsMemberStatisticsInfoExample();
            memberStatisticsInfoExample.createCriteria().andMemberIdEqualTo(umsMembers.get(0).getId());
            List<UmsMemberStatisticsInfo> umsMemberStatisticsInfos = memberStatisticsInfoMapper.selectByExample(memberStatisticsInfoExample);
            if (CollUtil.isNotEmpty(umsMemberStatisticsInfos)){
                UmsMemberStatisticsInfo memberStatisticsInfo = umsMemberStatisticsInfos.get(0);
                memberStatisticsInfo.setLoginCount(memberStatisticsInfo.getLoginCount()+1);
                memberStatisticsInfoMapper.updateByPrimaryKeySelective(memberStatisticsInfo);
            }
            UserDetails userDetails = loadUserByUsername(umsMembers.get(0).getUsername());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        }else {
            //没有该用户进行添加操作
            umsMember.setUsername("wx_"+sdf.format(new Date()));
            umsMember.setNickname(res.get("nickName").toString());
            umsMember.setPhone(null);
            umsMember.setCreateTime(new Date());
            umsMember.setStatus(1);
                umsMember.setCity(res.get("city").toString());
            umsMember.setGender((int)res.get("gender"));
            umsMember.setIcon(res.get("avatarUrl").toString());
            umsMember.setOpenId(res.get("openId").toString());
            //获取默认会员等级并设置
            UmsMemberLevelExample levelExample = new UmsMemberLevelExample();
            levelExample.createCriteria().andDefaultStatusEqualTo(1);
            List<UmsMemberLevel> memberLevelList = memberLevelMapper.selectByExample(levelExample);

            if (!CollectionUtils.isEmpty(memberLevelList)) {
                umsMember.setMemberLevelId(memberLevelList.get(0).getId());
            }
            int insert = memberMapper.insert(umsMember);
            UmsMemberStatisticsInfo memberStatisticsInfo = new UmsMemberStatisticsInfo();
            memberStatisticsInfo.setMemberId(umsMember.getId());
            memberStatisticsInfo.setConsumeAmount(new BigDecimal(0.00));
            memberStatisticsInfo.setOrderCount(0);
            memberStatisticsInfo.setCouponCount(0);
            memberStatisticsInfo.setCommentCount(0);
            memberStatisticsInfo.setReturnOrderCount(0);
            memberStatisticsInfo.setLoginCount(1);
            memberStatisticsInfo.setAttendCount(0);
            memberStatisticsInfo.setFansCount(0);
            memberStatisticsInfo.setCollectCommentCount(0);
            memberStatisticsInfo.setCollectProductCount(0);
            memberStatisticsInfo.setCollectSubjectCount(0);
            memberStatisticsInfo.setCollectTopicCount(0);
            memberStatisticsInfoMapper.insert(memberStatisticsInfo);
            UserDetails userDetails = loadUserByUsername(umsMember.getUsername());
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
            token = jwtTokenUtil.generateToken(userDetails);
        }
        tokenMap.put("phone",phone);
        tokenMap.put("token",token);
        return tokenMap;
    }

    @Override
    public void addPhone(WxLoginUserInfoVO wxLoginUserInfoVO) {
        String s = WXUtils.getUserInfo(wxLoginUserInfoVO.getEncryptedData(),wxLoginUserInfoVO.getSuccessKey(),wxLoginUserInfoVO.getIv()).toString();
        System.out.println("手机号码====="+s);
        Map<String,Object> res = JSON.parseObject(s,Map.class);
        UmsMember member = getCurrentMember();
        member.setPhone(res.get("phoneNumber").toString());
        memberMapper.updateByPrimaryKeySelective(member);
    }

    //对输入的验证码进行校验
    private boolean verifyAuthCode(String authCode, String telephone){
        if(StringUtils.isEmpty(authCode)){
            return false;
        }
        String realAuthCode = memberCacheService.getAuthCode(telephone);
        return authCode.equals(realAuthCode);
    }

}
